package com.zzw.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzw.reggie.common.CustomException;
import com.zzw.reggie.dto.SetmealDto;
import com.zzw.reggie.entity.Setmeal;
import com.zzw.reggie.entity.SetmealDish;
import com.zzw.reggie.mapper.SetmealMapper;
import com.zzw.reggie.service.ISetmealDishService;
import com.zzw.reggie.service.ISetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements ISetmealService {

    @Autowired
    private ISetmealDishService setmealDishService;

    /**
     * 新增套餐 同时新增套餐关联的菜品
     * @param setmealDto
     */
    @Override
    @Transactional
    public void saveSetmealWithDish(SetmealDto setmealDto) {
        //新增套餐表
        this.save(setmealDto);
        //新增套餐对应的菜品
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    @Transactional
    public void removeSetmealWithDish(List<Long> ids) {

        //select count(1) from setmeal where id in(1,2,3) and status = 1 如果sql查询出来的数据大于1 就代表正在售卖 反正可以删除
        //查询套餐是否在售卖
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(Setmeal::getId,ids);
        lqw.eq(Setmeal::getStatus,1);
        long count = this.count(lqw);
        //在售卖直接抛出业务异常
        if (count > 0){
            throw new CustomException("套餐正在售卖 不能删除");
        }
        //删除对应的套餐以及对象的菜品表
        //setmeal
        this.removeByIds(ids);
        //setmeal_dish
        //delete from setmeal_dish where setmealId in(1,2,4)
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(queryWrapper);

    }
}
